package com.combetter.changxing.viewmodel;

import android.app.Activity;
import android.app.Application;
import android.support.annotation.NonNull;

import com.combetter.changxing.MyApp;
import com.combetter.changxing.bluetooth.FacilityClient2;
import com.combetter.changxing.db.entity.UpLoadFacility;
import com.combetter.changxing.net.service.APIService;
import com.combetter.changxing.util.AppUtils;
import com.combetter.changxing.util.LogUtil;
import com.combetter.changxing.viewmodel.base.BaseViewModel;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by 深圳唐龙飞讯科技有限公司 on 2018/6/7.
 */

public class FacilityViewModel extends BaseViewModel {
    //已配对设备数据
//    public List<FacilityModel> facilityList = new ArrayList<>();

    public FacilityViewModel(@NonNull Application application) {
        super(application);
    }


//    /**
//     * 查询已配对设备
//     */
//    public void selectFacility() {
//        HashMap<String, String> map = new HashMap<>();
//        map.put("uid", MyApp.getInstance().getUserInfo().getUid());
//        map.put("type", "1");// 1：操作设备  2:收藏设备
//        LogUtil.e("查询已配对设备请求参数：", map);
//        mHttpRequest.createService(APIService.class)
//                .selectFacility(map)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(facilityHttpResult -> {
//                    LogUtil.e("查询已配对设备返回：", facilityHttpResult);
//                    if (facilityHttpResult.getCode() == 200) {
//                        facilityList.clear();
//                        facilityList = facilityHttpResult.getData();
//                        EventBus.getDefault().post(new EventMessage("selectFacility", ""));
//                    } else {
////                        ToastUtils.error(facilityHttpResult.getMsg());
//                    }
//                });
//    }


    /**
     * 上传设备
     */
    public void upLoadDBDevice(Activity activity) {
        List<UpLoadFacility> list = MyApp.getInstance().getDatabase().uploadFacilityDao().findByUid(MyApp.getInstance().getUserInfo().getUid());
        if (list != null && list.size() > 0 && AppUtils.isNetworkConnected(activity)) {
            for (UpLoadFacility upLoadFacility : list) {
                Observable.timer(1000, TimeUnit.MILLISECONDS).subscribe(aLong ->
                        insertFacility(activity, upLoadFacility.getFacilityAddress(), upLoadFacility.getFacilityName(), 1, upLoadFacility.getMid()));
            }
            MyApp.getInstance().getDatabase().uploadFacilityDao().deleteAll(MyApp.getInstance().getUserInfo().getUid());
        }
    }

    /**
     * 修改设备/添加设备
     */
    public void insertFacility(Activity activity, String identifierId, String name, int status, int mid) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("identifierId", identifierId);
        map.put("name", name);
        map.put("uid", MyApp.getInstance().getUserInfo().getUid());
        map.put("type", "1");
        if (mid != 0) {
            map.put("mid", mid);
        }
        map.put("status", status);
        LogUtil.e(" 修改设备/添加设备请求参数：", map);
//        LoadingDialog dialog = LoadingDialog.getInstance(activity);
//        dialog.show();
        mHttpRequest.createService(APIService.class)
                .insertFacility(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .doOnError(throwable -> {
                    UpLoadFacility upLoadFacility = MyApp.getInstance().getDatabase().uploadFacilityDao().findByMac(identifierId);
                    if (upLoadFacility == null) {
                        upLoadFacility = new UpLoadFacility();
                        upLoadFacility.setFacilityName(name);
                        upLoadFacility.setUid(MyApp.getInstance().getUserInfo().getUid());
                        upLoadFacility.setFacilityAddress(identifierId);
                        upLoadFacility.setMid(mid);
                        MyApp.getInstance().getDatabase().uploadFacilityDao().insertAllOrSingle(upLoadFacility);
                    }
                })
                .subscribe(httpResult -> {
                    LogUtil.e("修改设备/添加设备返回：", httpResult);
                    if (httpResult.getCode() == 200) {
                        if (status == 1) { //添加设备
//                            EventBus.getDefault().post(new EventMessage("addDeviceSuc", identifierId));
                        } else {//修改设备
                            byte[] value = name.getBytes();
                            byte[] data = new byte[16];
                            for (int i = 0; i < 16; i++) {
                                if (value.length - 1 < i) {
                                    data[i] = 0x00;
                                } else {
                                    data[i] = value[i];
                                }
                            }
                            FacilityClient2.getClient().sendName(data);
                        }
//
//                        Facility facility = new Facility();
//                        facility.setFacilityAddress(identifierId);
//                        facility.setFacilityName(name);
//                        MyApp.getInstance().getDatabase().facilityDao().insertFacility(facility);
//                        selectFacility();
                    } else {
                        if (status == 1 && httpResult.getCode() == 612) {
                            UpLoadFacility upLoadFacility = MyApp.getInstance().getDatabase().uploadFacilityDao().findByMac(identifierId);
                            if (upLoadFacility != null) {
                                MyApp.getInstance().getDatabase().uploadFacilityDao().deleteFacility(upLoadFacility);
                            }
                        }
//                        ToastUtils.error(httpResult.getMsg());
                    }
                });
    }

    /**
     * 删除设备/删除收藏设备
     *
     * @param context 上下文
     */
//    public void deleteFacility(Activity context, int mid) {
//        String uid = MyApp.getInstance().getUserInfo().getUid();
//        LogUtil.e(" 删除设备：{mid:" + mid + ",uid:" + uid + ",\"type\":1}");
//        LoadingDialog dialog = LoadingDialog.getInstance(context);
//        dialog.show();
//        mHttpRequest.createService(APIService.class)
//                .deleteFacility(mid, uid, 1)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .doOnError(throwable -> dialog.dismiss())
//                .subscribe(httpResult -> {
//                    dialog.dismiss();
//                    if (httpResult.getCode() == 200) {
//                        MyApp.getInstance().resetFacilityInfo();
//                        ToastUtils.success("删除成功");
////                        selectFacility();
//                    } else {
//                        ToastUtils.error(httpResult.getMsg());
//                    }
//                });
//    }
}
